<template>
  <ms-dialog
    width="90%"
    center-scroll
    ok-btn="配置"
    :title="title"
    :dialog-visible="dialogVisible"
    @show="showDialog"
    @ok="handleSaveForm"
    @close="handleCloseDialog"
  >
    <el-divider content-position="left">
      表单信息配置
    </el-divider>
    <ms-dnyc-table
      add-row
      :table-props="tableProps"
      :data-source="tablesData"
    >
    </ms-dnyc-table>
  </ms-dialog>
</template>

<script>
// mixins
import tip from '@/mixins/tip'

// components
import MsDialog from '@/common/dialog'
import { MsDnycTable } from '@/common/table'

// api
import { asynTable } from '@/api/generCode'
import { columnList, updatTable } from '@/api/tableInfo'

export default {
  components: {
    MsDialog,
    MsDnycTable
  },
  mixins: [tip],
  data() {
    return {
      tableProps: [
        { index: 'id', label: '标识', minWidth: true },
        { index: 'cname', label: '字段名', type: 'input' },
        { index: 'ctype', label: '类型', type: 'input' },
        { index: 'clength', label: '长度', type: 'input' },
        { index: 'ccomment', label: '标签名称', type: 'input' }
      ],
      tablesData: [],
      baseConf: {},
      validDialog: false,
      // 直接指向地址 对象只存储传递
      validData: {},
      cacheData: []
    }
  },
  methods: {
    showDialog() {
      columnList(this.formId).then(res => {
        const { obj } = res
        this.tablesData = obj
        this.cacheData = JSON.parse(JSON.stringify(obj))
      })
    },
    handleSaveForm() {
      const newData = this.tablesData.map((item) => {
        const data = {}
        const compare = this.cacheData.find((innerItem) => item.id === innerItem.id)

        if (!compare) {
          return item
        }
        data.cname = `${compare.cname},${item.cname}`

        if (item.ctype !== compare.ctype) {
          data.ctype = item.ctype
        }

        if (item.ccomment !== compare.ccomment) {
          data.ccomment = item.ccomment
        }

        if (item.clength !== compare.clength) {
          data.clength = item.clength
        }

        return data
      }).filter(item => Object.keys(item).length > 0)
      updatTable(newData, this.formId).then(res => {
        this.handleResultOper(res)
      })
    },
    handleBeforeCloseDialog() {
      this.tablesData = []
      this.baseConf = {}
    },
    // 同步表数据
    handleClickAsyncTable() {
      asynTable(this.formId).then(res => {
        const { tablesData } = this
        const newData = res.obj
        const newTablesData = newData.map(item => {
          const column = this._.cloneDeep(tablesData.filter(innerItem => (innerItem.colName === item.colName)))
          return this._.extend(column.length ? column[0] : {}, item)
        })
        this.tablesData = newTablesData
      })
    },
    // 表单校验按钮
    handleClickValid(index) {
      const currentRow = this.tablesData[index]
      this.validData = currentRow
      this.validDialog = true
    }
  }
}
</script>
